package org.telegram.bot.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.telegram.bot.domain.BotGroup;
import org.telegram.bot.domain.BotJob;
import org.telegram.bot.mapper.BotJobMapper;
import org.telegram.bot.service.IBotChatMemberService;
import org.telegram.bot.service.IBotGroupService;
import org.telegram.bot.service.IBotJobService;

import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 定时任务Service业务层处理
 *
 * @author wyx
 * @date 2024-11-25
 */
@Slf4j
@Service
public class BotJobServiceImpl implements IBotJobService
{
    @Resource
    private BotJobMapper botJobMapper;
    
    @Resource
    private IBotChatMemberService botChatMemberService;
    
    @Resource
    private IBotGroupService botGroupService;
    
    @Resource
    private ISysJobService jobService;
    /**
     * 查询定时任务
     *
     * @param id 定时任务主键
     * @return 定时任务
     */
    @Override
    public BotJob selectBotJobById(Long id)
    {
        BotJob botJob = botJobMapper.selectById(id);
        if(botJob==null){
            throw new ServiceException("定时任务不存在");
        }
        SysJob sysJob = jobService.selectJobById(botJob.getJobId());
        if(sysJob==null){
            throw new ServiceException("系统定时任务不存在");
        }
        botJob.setCronExpression(sysJob.getCronExpression());
        return botJob;
    }

    /**
     * 查询定时任务列表
     *
     * @param botJob 定时任务
     * @return 定时任务
     */
    @Override
    public List<BotJob> selectBotJobList(BotJob botJob)
    {
        List<Long> joinChatList = botChatMemberService.getJoinChatList();
        if(!CollectionUtils.isEmpty(joinChatList)){
            botJob.setChatIds(joinChatList);
        }else{
            return new ArrayList<>();
        }
        List<BotJob> botJobs = botJobMapper.selectBotJobList(botJob);
        //将群组名称放入
        if(!CollectionUtils.isEmpty(botJobs)){
            Map<Long, BotGroup> groupMap = botGroupService.selectGroupToMap(joinChatList);
            for (BotJob job : botJobs) {
                BotGroup botGroup = groupMap.get(job.getChatId());
                if(botGroup!=null){
                    job.getParams().put("chatName",botGroup.getTitle());
                }
            }
        }
        return botJobs;
    }

    /**
     * 新增定时任务
     *
     * @param botJob 定时任务
     * @return 结果
     */
    @Override
    public int insertBotJob(BotJob botJob)
    {
        return botJobMapper.insert(botJob);
    }

    /**
     * 修改定时任务
     *
     * @param botJob 定时任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBotJob(BotJob botJob) throws SchedulerException, TaskException {
        
        int i = 0;
        //如果id为空则插入
        if(botJob.getId()==null){
            SysJob sysJob = new SysJob();
            sysJob.setStatus(botJob.getStatus());
            sysJob.setJobName(botJob.getName());
            sysJob.setCronExpression(botJob.getCronExpression());
            botJob.setId(IdUtil.getSnowflakeNextId());
            sysJob.setJobGroup("BOT");
            sysJob.setConcurrent("1");
            sysJob.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
            sysJob.setInvokeTarget("botTask.execute("+botJob.getId()+"L)");
            jobService.insertJob(sysJob);
            
            botJob.setJobId(sysJob.getJobId());
            i = insertBotJob(botJob);
        }else{
            //botJobMapper查询jobId的值
            BotJob oldBotJob = botJobMapper.selectById(botJob.getId());
            if(oldBotJob==null){
                throw new ServiceException("定时任务不存在");
            }
            SysJob oldSysJob = jobService.selectJobById(oldBotJob.getJobId());
            if(oldSysJob==null){
                throw new ServiceException("系统定时任务不存在，请重新创建");
            }
            oldSysJob.setStatus(botJob.getStatus());
            oldSysJob.setJobName(botJob.getName());
            oldSysJob.setCronExpression(botJob.getCronExpression());
            //oldSysJob.setInvokeTarget("botTask.execute("+botJob.getId()+"L)");
            jobService.updateJob(oldSysJob);
            
           i = botJobMapper.updateById(botJob);
        }
        
        return i;
    }

    /**
     * 批量删除定时任务
     *
     * @param ids 需要删除的定时任务主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBotJobByIds(Long[] ids) throws SchedulerException {
        List<BotJob> botJobs = botJobMapper.selectBatchIds(Arrays.asList(ids));
        int rows = botJobMapper.deleteByIds(Arrays.asList(ids));
        //sysJobIds转数组Long[]
        Long[] jobIdsArray = botJobs.stream().map(BotJob::getJobId).toArray(Long[]::new);
        jobService.deleteJobByIds(jobIdsArray);
        return rows;
    }

    /**
     * 删除定时任务信息
     *
     * @param id 定时任务主键
     * @return 结果
     */
    @Override
    public int deleteBotJobById(Long id)
    {
        return botJobMapper.deleteById(id);
    }
}
